/*
包含n 个用来创建action 的工厂函数(action creator)
*/
import { SET_HEAD_TITLE, RECEIVE_USER,RESET_USER,SHOW_ERROR_MSG} from './action-types'
import {reqLogin} from '../api'
import storageUtils from "../utils/storageUtils";
import memoryUtils from "../utils/memoryUtils";
import {Modal} from "antd";


/*
设置头部标题的同步action
*/
export const setHeadTitle = (headTitle) => ({type: SET_HEAD_TITLE, data: headTitle})
/*接收用户的同步 action */
export const receiveUser = (user) => ({type: RECEIVE_USER, user})
/*显示错误信息的同步 action */
export const showErrorMsg = (errorMsg) => ({type: SHOW_ERROR_MSG, errorMsg})
/*退出登陆的同步 action */
export const logout = () => {
    storageUtils.removeUser()
    return {type: RESET_USER}
}
/*登陆的异步 action */
export const login = (username, password) => {
    return async dispatch => {
        const result = await reqLogin(username, password)
        if (result.code === 200) {
            const user = result.data
            storageUtils.saveUser(user)
            memoryUtils.user=user
            dispatch(receiveUser(user))
            Modal.success({content:"登录成功"})
        } else {
            const msg = result.msg
            dispatch(showErrorMsg(msg))
        }
    }
}